package com.yc.ssq.servlet;

import com.google.gson.Gson;
import com.yc.common.bean.Result;
import com.yc.ssq.dao.SsqDao;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

@MultipartConfig
@WebServlet(name = "UploadServlet", value = "/upload.s")
public class UploadServlet extends HttpServlet {

    private SsqDao dao = new SsqDao();
    private static final String UPLOAD_DIR = "D:\\study\\study_work\\ssq\\";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        //假设上传文件字段file
        Part filepart = request.getPart("file");
        //构建文件对象
        String diskpath = UPLOAD_DIR + filepart.getSubmittedFileName();

        File fileObj = new File(diskpath);

        //获取相应流
        PrintWriter out = response.getWriter();
        response.setContentType("application/json;charset=UTF-8");

        //判断文件是否存在
        if (fileObj.exists()) {
            Result res = Result.failure("文件已经存在,文件上传失败", null);
            String json = new Gson().toJson(res);
            out.append(json);
        } else {
            filepart.write(diskpath);
            dao.sava(fileObj);
            Result res = Result.success("文件上传成功！", null);
            String json = new Gson().toJson(res);
            out.append(json);
        }
    }
}
